package com.example.contentprovider

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.contentValuesOf
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val dbhelper = MyDB(this, "bookstore.db", 1)
        val db = dbhelper.writableDatabase
        val row1 = contentValuesOf("name" to "book1", "price" to "10.1")
        db.insert("book", null, row1)
        val row2 = contentValuesOf( "name" to "c1", "type" to "t1")
        db.insert("category", null, row2)

        // for test 进程内通信
        val b = findViewById<Button>(R.id.button)
        b.setOnClickListener{
            val uri = Uri.parse("content://com.example.contentprovider.provider/book")
            contentResolver.query(uri,null,null,null,null)?.apply {
                while(moveToNext()){
                    val name = getString(getColumnIndex("name"))
                    val price = getDouble(getColumnIndex("price"))
                    Log.d(javaClass.simpleName, "onCreate: $name,$price")
                }
                close()
            }
        }
    }
}


class MyDB(context: Context, name:String, version:Int): SQLiteOpenHelper(context,name,null,version)
{
    val createBook = "create table book  ("+
            "id Integer primary key autoincrement,"+
            "name text,"+
            "price real)"
    val createCategory = "create table category  ("+
            "name text,"+
            "type text)"

    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL(createBook)
        db?.execSQL(createCategory)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        TODO("Not yet implemented")
    }
}

